/** 
 * This file is a part of qloudgen-sec. 
 * You can redistribute qloudgen-sec and/or modify it under the terms of the Lesser GNU General Public License version 3. 
 * qloudgen-sec is distributed WITHOUT ANY WARRANTY. 
 *
 * See the Lesser GNU General Public License for more details at http://www.gnu.org/licenses/. 
 **/
package org.qloudgen.sec.util;

import java.io.InputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>Title: Common Resource</p>
 * <p>Description: Common resource implementation.</p>
 * <p>Copyright: qloudgen/sec 2012</p>
 * @author <a href="mailto:hyq.dd.sun@gmail.com">glue.3M</a>
 */
public final class ResourceUtil {
	/**
	 * Log output.
	 */
	private final static Logger logger = LoggerFactory.getLogger( ResourceUtil.class );
	/**
	 * Resource path prefix that specifies to load from a classpath location.
	 */
	public static final String PREFIX_CLASSPATH = "classpath:";
	/**
	 * Resource path prefix that specifies to load from a url location.
	 */
	public static final String PREFIX_URL = "url:";
	/**
	 * Resource path prefix that specifies to load from a file location.
	 */
	public static final String PREFIX_FILE = "file:";
	
	/**
	 * Default constructor.
	 */
	private ResourceUtil() {
	}
	
	/**
	 * Returns current stream by path.
	 *
	 * @param path
	 * @return InputStream
	 */
	public static InputStream getInputStream(String path) {
		//
		try {
			InputStream is = null;
			if ( path.startsWith( PREFIX_CLASSPATH ) ) {
			    is = loadFromClassPath( StringUtil.afterString( path , PREFIX_CLASSPATH ) );
			}
			else if ( path.startsWith( PREFIX_URL ) ) {
			    is = loadFromUrl( StringUtil.afterString( path , PREFIX_URL ) );
			}
			else if ( path.startsWith( PREFIX_FILE ) ) {
			    is = loadFromFile( StringUtil.afterString( path , PREFIX_FILE ) );
			}
			else {
			    is = loadFromFile( path );
			}
			return is;
		}
		catch (Throwable t) {
			logger.trace( "Unable to load stream from current path...{}" , path );
			logger.trace( "\n{}" , ExceptionUtil.get( t ) );
			throw new RuntimeException( t );
		}
	}
	
	/**
	 * Returns current file stream by path.
	 *
	 * @param path
	 * @return InputStream
	 * @throws IOException
	 */
	private static InputStream loadFromFile(String path) throws IOException {
		return new FileInputStream( path );
	}
	
	/**
	 * Returns current url stream by path.
	 *
	 * @param path
	 * @return InputStream
	 * @throws IOException
	 */
	private static InputStream loadFromUrl(String path) throws IOException {
		return ( new URL( path ) ).openStream();
	}
	
	/**
	 * Returns current classpath stream by path.
	 *
	 * @param path
	 * @return InputStream
	 */
	private static InputStream loadFromClassPath(String path) {
		return ClassUtil.getResourceAsStream( path );
	}
}